<?php
if (!defined('__TYPECHO_ROOT_DIR__')) {
    exit;
}

// 检测Typecho版本并导入对应的类
if (class_exists('\\Typecho\\Widget')) {
    // Typecho 1.2+ (命名空间版本)
    require_once __TYPECHO_ROOT_DIR__ . '/var/Utils/PasswordHash.php';
    if (!class_exists('PasswordHash')) {
        class_alias('Utils\\PasswordHash', 'PasswordHash');
    }
} else {
    // 旧版Typecho
    if (file_exists(__TYPECHO_ROOT_DIR__ . '/var/Utils/PasswordHash.php')) {
        require_once __TYPECHO_ROOT_DIR__ . '/var/Utils/PasswordHash.php';
    } else if (file_exists(__TYPECHO_ROOT_DIR__ . '/var/Typecho/PasswordHash.php')) {
        require_once __TYPECHO_ROOT_DIR__ . '/var/Typecho/PasswordHash.php';
    }
}

class QidaoConnect_Widget extends Widget_Abstract_Users
{
    private $referer = ''; // 来源页面
    private $auth = [];
    private $connect = [];
    
    /**
     * 风格目录
     *
     * @access private
     * @var string
     */
    private $_themeDir;

    public function __construct($request, $response, $params = null)
    {
        parent::__construct($request, $response, $params);
        $this->_themeDir = rtrim($this->options->themeFile($this->options->theme), '/') . '/';

        // 初始化皮肤函数
        $functionsFile = $this->_themeDir . 'functions.php';
        if (file_exists($functionsFile)) {
            require_once $functionsFile;
            if (function_exists('themeInit')) {
                themeInit($this);
            }
        }
    }

    /**
     * 获取OAuth登录地址，重定向
     *
     * @access public
     */
    public function oauth()
    {
        // 获取插件配置
        $options = $this->options->plugin('QidaoConnect');
        $clientId = $options->app_id;
        $scope = $options->scope;
        $callback = $options->callback;
        
        if (empty($clientId)) {
            throw new Typecho_Widget_Exception("栖岛OAuth2配置不完整，请先配置应用ID！");
        }
        
        // 储存当前来源页面
        if (session_status() != PHP_SESSION_ACTIVE) {
            session_set_cookie_params(3600);
            session_start();
        }
        
        $this->referer = isset($_COOKIE['QidaoConnect_Referer']) ? urldecode($_COOKIE['QidaoConnect_Referer']) : $this->request->getReferer();
        setcookie("QidaoConnect_Referer", "", time() - 3600);
        
        if (strpos($this->referer, $this->options->index) === 0) {
            // 站内来源页放入session
            $_SESSION['QidaoConnect_Referer'] = $this->referer;
        }
        
        // 生成state参数，防止CSRF攻击
        $state = md5(uniqid(rand(), true));
        $_SESSION['qidao_state'] = $state;
        
        // 构建授权URL
        $authorizeUrl = 'https://api.qidao.tvcloud.top/oauth2/authorize?' . http_build_query([
            'response_type' => 'code',
            'client_id' => $clientId,
            'redirect_uri' => $callback,
            'scope' => $scope,
            'state' => $state
        ]);
        
        // 重定向到授权页面
        $this->response->redirect($authorizeUrl);
    }

    /**
     * OAuth2回调处理
     *
     * @access public
     */
    public function callback()
    {
        // 开启session
        if (session_status() != PHP_SESSION_ACTIVE) {
            session_set_cookie_params(3600);
            session_start();
        }
        
        // 创建日志文件
        $logFile = __DIR__ . '/qidao_debug.log';
        file_put_contents($logFile, "回调开始，Session ID: " . session_id() . "\n", FILE_APPEND);
        file_put_contents($logFile, "回调开始，Session状态: " . print_r($_SESSION, true) . "\n", FILE_APPEND);
        
        // 先获取可能存在的会话数据
        $this->auth = isset($_SESSION['__typecho_auth']) ? $_SESSION['__typecho_auth'] : [];
        $this->connect = isset($_SESSION['__typecho_qidao_connect']) ? $_SESSION['__typecho_qidao_connect'] : [];
        
        // 从session中获取来源页
        $this->referer = isset($_SESSION['QidaoConnect_Referer']) ? $_SESSION['QidaoConnect_Referer'] : '';
        
        // 清理可能存在的之前未完成的授权数据，避免状态混乱
        if (isset($_GET['code']) && isset($_GET['state']) && !isset($_SESSION['__qidao_oauth_processed'])) {
            // 仅保留状态验证相关的session数据，清除可能存在的旧授权数据
            $tmpState = isset($_SESSION['qidao_state']) ? $_SESSION['qidao_state'] : '';
            $tmpReferer = isset($_SESSION['QidaoConnect_Referer']) ? $_SESSION['QidaoConnect_Referer'] : '';
            $tmpAuth = isset($_SESSION['__typecho_auth']) ? $_SESSION['__typecho_auth'] : [];
            $tmpConnect = isset($_SESSION['__typecho_qidao_connect']) ? $_SESSION['__typecho_qidao_connect'] : [];
            
            // 保存旧授权数据便于日志分析
            file_put_contents($logFile, "旧授权数据(auth): " . print_r($tmpAuth, true) . "\n", FILE_APPEND);
            file_put_contents($logFile, "旧授权数据(connect): " . print_r($tmpConnect, true) . "\n", FILE_APPEND);
            
            // 在获取新的token前才清除旧数据
            // 暂时不清除 - 因为这可能导致数据丢失问题
            
            // 标记为已处理过，避免重复处理
            $_SESSION['__qidao_oauth_processed'] = true;
            
            file_put_contents($logFile, "已处理OAuth请求，不清除旧授权数据\n", FILE_APPEND);
        }
        
        unset($_SESSION['QidaoConnect_Referer']);
        
        // 处理表单提交
        if ($this->request->isPost()) {
            $do = $this->request->get('do');
            if (!in_array($do, ['bind', 'reg'])) {
                throw new Typecho_Widget_Exception("无效的请求！");
            }
            
            if (!isset($this->auth['openid'])) {
                $this->response->redirect(empty($this->referer) ? $this->options->index : $this->referer);
            }
            
            $func = 'doCallback' . ucfirst($do);
            $this->$func();
            
            unset($_SESSION['__typecho_auth']);
            unset($_SESSION['__typecho_qidao_connect']);
            
            $this->response->redirect(empty($this->referer) ? $this->options->index : $this->referer);
        }
        
        // 第三方登录回调处理
        if (empty($this->auth)) {
            $code = $this->request->get('code', '');
            $state = $this->request->get('state', '');
            
            // 验证state防止CSRF攻击
            if (empty($code) || empty($state) || !isset($_SESSION['qidao_state']) || $state !== $_SESSION['qidao_state']) {
                unset($_SESSION['qidao_state']);
                $this->response->redirect($this->options->index);
                return;
            }
            unset($_SESSION['qidao_state']);
            
            // 获取插件配置
            $options = $this->options->plugin('QidaoConnect');
            $clientId = $options->app_id;
            $clientSecret = $options->app_secret;
            $redirectUri = $options->callback;
            
            if (empty($clientId) || empty($clientSecret)) {
                throw new Typecho_Widget_Exception("栖岛OAuth2配置不完整！");
            }
            
            // 请求access_token
            $tokenUrl = 'https://api.qidao.tvcloud.top/oauth2/token';
            $postData = [
                'grant_type' => 'authorization_code',
                'client_id' => $clientId,
                'client_secret' => $clientSecret,
                'code' => $code,
                'redirect_uri' => $redirectUri
            ];
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $tokenUrl);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            $response = curl_exec($ch);
            curl_close($ch);
            
            $token = json_decode($response, true);
            
            if (!isset($token['access_token'])) {
                throw new Typecho_Widget_Exception("获取栖岛OAuth2令牌失败！");
            }
            
            // 获取用户信息 - 添加详细的错误处理和调试信息
            // 尝试两种方式获取用户信息: 1. 使用Bearer令牌认证 2. 使用access_token参数
            $userData = null;
            
            // 创建调试日志文件
            $logFile = __DIR__ . '/qidao_debug.log';
            file_put_contents($logFile, "开始OAuth授权回调处理\n", FILE_APPEND);
            file_put_contents($logFile, "获取到的令牌: " . print_r($token, true) . "\n", FILE_APPEND);
            
            // 方法1: 使用Bearer令牌认证
            try {
                $userinfoUrl = 'https://api.qidao.tvcloud.top/oauth2/userinfo/oauth';
                file_put_contents($logFile, "尝试方法1: Bearer令牌认证\n", FILE_APPEND);
                
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $userinfoUrl);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $token['access_token']]);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                $response = curl_exec($ch);
                
                // 记录curl错误
                if ($response === false) {
                    file_put_contents($logFile, "Curl错误: " . curl_error($ch) . "\n", FILE_APPEND);
                } else {
                    file_put_contents($logFile, "API响应: " . $response . "\n", FILE_APPEND);
                }
                
                curl_close($ch);
                
                $userInfo = json_decode($response, true);
                
                if (isset($userInfo['code']) && $userInfo['code'] == 1 && isset($userInfo['data']['uid'])) {
                    $userData = $userInfo;
                    file_put_contents($logFile, "方法1成功获取用户信息\n", FILE_APPEND);
                } else {
                    file_put_contents($logFile, "方法1失败: " . json_encode($userInfo) . "\n", FILE_APPEND);
                }
            } catch (Exception $e) {
                file_put_contents($logFile, "方法1异常: " . $e->getMessage() . "\n", FILE_APPEND);
            }
            
            // 方法2: 使用access_token参数
            if (!$userData) {
                try {
                    $userinfoUrl = 'https://api.qidao.tvcloud.top/oauth2/userinfo/oauth?access_token=' . $token['access_token'];
                    file_put_contents($logFile, "尝试方法2: access_token参数\n", FILE_APPEND);
                    
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $userinfoUrl);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                    $response = curl_exec($ch);
                    
                    // 记录curl错误
                    if ($response === false) {
                        file_put_contents($logFile, "Curl错误: " . curl_error($ch) . "\n", FILE_APPEND);
                    } else {
                        file_put_contents($logFile, "API响应: " . $response . "\n", FILE_APPEND);
                    }
                    
                    curl_close($ch);
                    
                    $userInfo = json_decode($response, true);
                    
                    if (isset($userInfo['code']) && $userInfo['code'] == 1 && isset($userInfo['data']['uid'])) {
                        $userData = $userInfo;
                        file_put_contents($logFile, "方法2成功获取用户信息\n", FILE_APPEND);
                    } else {
                        file_put_contents($logFile, "方法2失败: " . json_encode($userInfo) . "\n", FILE_APPEND);
                    }
                } catch (Exception $e) {
                    file_put_contents($logFile, "方法2异常: " . $e->getMessage() . "\n", FILE_APPEND);
                }
            }
            
            // 如果两种方法都失败，尝试直接使用access_token作为uid (应急方案)
            if (!$userData && !empty($token['access_token'])) {
                file_put_contents($logFile, "尝试应急方案: 使用access_token作为标识\n", FILE_APPEND);
                
                // 构造最小可用的用户数据结构
                $userData = [
                    'code' => 1,
                    'data' => [
                        'uid' => substr(md5($token['access_token']), 0, 8),
                        'name' => '栖岛用户',
                        'screenName' => '栖岛用户_' . substr(md5($token['access_token']), 0, 4),
                        'avatar' => ''
                    ]
                ];
                file_put_contents($logFile, "应急方案构造的用户数据: " . json_encode($userData) . "\n", FILE_APPEND);
            }
            
            if (!$userData || !isset($userData['code']) || $userData['code'] != 1 || !isset($userData['data']['uid'])) {
                file_put_contents($logFile, "全部方法失败，无法获取用户信息\n", FILE_APPEND);
                throw new Typecho_Widget_Exception("获取栖岛用户信息失败！请查看插件目录下的qidao_debug.log文件了解详情。");
            }
            
            // 使用成功获取的数据
            $userInfo = $userData;
            
            $userData = $userInfo['data'];
            file_put_contents($logFile, "处理用户数据: " . print_r($userData, true) . "\n", FILE_APPEND);
            
            // 确保所有必要的字段都存在，防止undefined index错误
            $userUid = isset($userData['uid']) ? $userData['uid'] : substr(md5($token['access_token']), 0, 8);
            $userName = isset($userData['name']) ? $userData['name'] : '栖岛用户';
            $userScreenName = isset($userData['screenName']) ? $userData['screenName'] : 
                             (isset($userData['name']) ? $userData['name'] : '栖岛用户_'.substr(md5($token['access_token']), 0, 4));
            $userAvatar = isset($userData['avatar']) ? $userData['avatar'] : '';
            $userEmail = isset($userData['mail']) ? $userData['mail'] : '';
            
            file_put_contents($logFile, "用户关键信息: uid={$userUid}, name={$userName}, email={$userEmail}\n", FILE_APPEND);
            
            // 存储邮箱到session，确保在多次处理过程中不会丢失
            $_SESSION['qidao_user_email'] = $userEmail;
            
            // 存储用户信息
            $connect = [
                'uid' => 0,
                'openid' => $userUid,
                'access_token' => $token['access_token'],
                'refresh_token' => isset($token['refresh_token']) ? $token['refresh_token'] : '',
                'expires_in' => isset($token['expires_in']) ? (time() + intval($token['expires_in'])) : 0,
                'name' => $userName,
                'nickname' => $userScreenName,
                'gender' => 0, // 默认性别未知
                'head_img' => $userAvatar
                // 不要在connect中存储email字段，因为数据库表中没有这个字段
            ];
            
            file_put_contents($logFile, "创建connect数据: " . print_r($connect, true) . "\n", FILE_APPEND);
            
            $this->auth = [
                'openid' => $userUid,
                'nickname' => $userScreenName
            ];
            file_put_contents($logFile, "创建auth数据: " . print_r($this->auth, true) . "\n", FILE_APPEND);
            
            // 存储到session
            $_SESSION['__typecho_auth'] = $this->auth;
            $_SESSION['__typecho_qidao_connect'] = $connect;
            
            // 重新赋值connect，确保后续使用
            $this->connect = $connect;
            
            // 写入日志
            file_put_contents($logFile, "完成OAuth授权，获取到用户信息，准备处理登录\n", FILE_APPEND);
            file_put_contents($logFile, "重新赋值后的connect数据: " . print_r($this->connect, true) . "\n", FILE_APPEND);
        }
        
        // 判断用户登录状态
        if ($this->user->hasLogin()) {
            // 已登录状态，直接绑定账号
            $this->bindUser($this->user->uid, $this->connect);
            $this->widget('Widget_Notice')->set(['成功绑定栖岛账号！']);
            
            // 强制设置登录状态
            $this->forceSetLoginStatus($this->user->uid);
            
            // 使用安全重定向
            $redirectUrl = empty($this->referer) ? $this->options->index : $this->referer;
            $this->safeRedirect($redirectUrl);
        } else {
            // 未登录状态，查询是否已绑定
            file_put_contents($logFile, "用户未登录，查询是否已有绑定关系\n", FILE_APPEND);
            file_put_contents($logFile, "当前this->connect: " . print_r($this->connect, true) . "\n", FILE_APPEND);
            file_put_contents($logFile, "当前SESSION connect: " . print_r(isset($_SESSION['__typecho_qidao_connect']) ? $_SESSION['__typecho_qidao_connect'] : '未设置', true) . "\n", FILE_APPEND);
            
            // 尝试从session恢复connect数据
            if (empty($this->connect) && isset($_SESSION['__typecho_qidao_connect'])) {
                $this->connect = $_SESSION['__typecho_qidao_connect'];
                file_put_contents($logFile, "从session恢复connect数据\n", FILE_APPEND);
            }
            
            // 确保openid存在后再查询
            if (empty($this->connect) || !isset($this->connect['openid']) || empty($this->connect['openid'])) {
                file_put_contents($logFile, "错误：connect数据中缺少openid\n", FILE_APPEND);
                
                // 尝试从auth数据中恢复openid
                if (isset($this->auth['openid']) && !empty($this->auth['openid'])) {
                    file_put_contents($logFile, "尝试从auth中恢复openid: " . $this->auth['openid'] . "\n", FILE_APPEND);
                    
                    if (empty($this->connect)) {
                        $this->connect = [
                            'openid' => $this->auth['openid'],
                            'access_token' => isset($_SESSION['access_token']) ? $_SESSION['access_token'] : '',
                            'refresh_token' => '',
                            'expires_in' => 0,
                            'name' => isset($this->auth['nickname']) ? $this->auth['nickname'] : '',
                            'nickname' => isset($this->auth['nickname']) ? $this->auth['nickname'] : '',
                            'gender' => 0,
                            'head_img' => ''
                            // 不要添加email字段
                        ];
                        file_put_contents($logFile, "已创建基本connect数据\n", FILE_APPEND);
                    } else {
                        $this->connect['openid'] = $this->auth['openid'];
                        file_put_contents($logFile, "已为connect设置openid\n", FILE_APPEND);
                    }
                } else {
                    file_put_contents($logFile, "无法恢复openid，重定向到首页\n", FILE_APPEND);
                    $this->widget('Widget_Notice')->set(['获取用户信息失败，请重试'], 'error');
                    $this->response->redirect($this->options->index);
                    return;
                }
            }
            
            // 使用try-catch包裹查询，增强错误处理
            try {
                // 确保表存在
                $tableExists = false;
                try {
                    $this->db->fetchRow($this->db->select('id')->from('table.qidao_connect')->limit(1));
                    $tableExists = true;
                } catch (Exception $e) {
                    // 如果表不存在，尝试创建
                    file_put_contents($logFile, "qidao_connect表可能不存在，尝试创建: " . $e->getMessage() . "\n", FILE_APPEND);
                    $prefix = $this->db->getPrefix();
                    $sql = "CREATE TABLE IF NOT EXISTS `{$prefix}qidao_connect` (
                        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                        `uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
                        `openid` char(50) NOT NULL,
                        `access_token` varchar(255) NOT NULL DEFAULT '0' COMMENT '用户对应access_token',
                        `refresh_token` varchar(255) NOT NULL DEFAULT '0' COMMENT '刷新有效期token',
                        `expires_in` int(10) unsigned NOT NULL DEFAULT '0',
                        `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后登录',
                        `name` varchar(38) NOT NULL DEFAULT '0',
                        `nickname` varchar(38) NOT NULL DEFAULT '0',
                        `gender` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '性别0未知,1男,2女',
                        `head_img` varchar(255) NOT NULL DEFAULT '0' COMMENT '头像',
                        PRIMARY KEY (`id`),
                        KEY `uid` (`uid`),
                        KEY `openid` (`openid`)
                    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
                    
                    try {
                        $this->db->query($sql);
                        $tableExists = true;
                        file_put_contents($logFile, "成功创建qidao_connect表\n", FILE_APPEND);
                    } catch (Exception $e2) {
                        file_put_contents($logFile, "创建qidao_connect表失败: " . $e2->getMessage() . "\n", FILE_APPEND);
                    }
                }
                
                if ($tableExists) {
                    // 使用参数化查询，避免SQL注入
                    $openid = $this->connect['openid'];
                    file_put_contents($logFile, "查询绑定关系，openid = " . $openid . "\n", FILE_APPEND);
                    
                    // 添加额外的类型检查和转换
                    if (!is_string($openid) && !is_numeric($openid)) {
                        file_put_contents($logFile, "警告：openid不是字符串或数字类型: " . gettype($openid) . "\n", FILE_APPEND);
                        if (is_array($openid) || is_object($openid)) {
                            file_put_contents($logFile, "尝试将复杂类型转换为字符串\n", FILE_APPEND);
                            $openid = strval($openid);
                        }
                    }
                    
                    // 确保openid是字符串
                    $openid = strval($openid);
                    
                    // 使用参数化查询
                    $connectRecord = $this->db->fetchRow($this->db->select()
                        ->from('table.qidao_connect')
                        ->where('openid = ?', $openid)
                        ->limit(1));
                    
                    file_put_contents($logFile, "参数化查询结果: " . print_r($connectRecord, true) . "\n", FILE_APPEND);
                    
                    // 如果参数化查询失败，尝试直接SQL查询作为备份方案
                    if (!$connectRecord) {
                        file_put_contents($logFile, "参数化查询无结果，尝试直接SQL查询\n", FILE_APPEND);
                        try {
                            // 由于没有escape方法，我们手动处理特殊字符
                            $safeOpenid = str_replace("'", "''", $openid); // SQL注入防护，双写单引号
                            
                            $sql = "SELECT * FROM `{$this->db->getPrefix()}qidao_connect` WHERE `openid` = '{$safeOpenid}' LIMIT 1";
                            file_put_contents($logFile, "执行SQL: " . $sql . "\n", FILE_APPEND);
                            $connectRecord = $this->db->fetchRow($this->db->query($sql));
                            file_put_contents($logFile, "直接SQL查询结果: " . print_r($connectRecord, true) . "\n", FILE_APPEND);
                        } catch (Exception $e) {
                            file_put_contents($logFile, "直接SQL查询失败: " . $e->getMessage() . "\n", FILE_APPEND);
                        }
                    }
                    
                    if ($connectRecord) {
                        $isConnect = $connectRecord;
                        file_put_contents($logFile, "成功找到绑定关系\n", FILE_APPEND);
                    } else {
                        // 检查是否可能是MySQL版本导致的大小写敏感问题
                        try {
                            // 尝试使用LOWER函数进行不区分大小写的查询
                            $sql = "SELECT * FROM `{$this->db->getPrefix()}qidao_connect` WHERE LOWER(`openid`) = LOWER('{$safeOpenid}') LIMIT 1";
                            file_put_contents($logFile, "尝试不区分大小写的查询: " . $sql . "\n", FILE_APPEND);
                            $caseInsensitiveRecord = $this->db->fetchRow($this->db->query($sql));
                            
                            if ($caseInsensitiveRecord) {
                                file_put_contents($logFile, "通过不区分大小写的查询找到记录\n", FILE_APPEND);
                                $isConnect = $caseInsensitiveRecord;
                            } else {
                                $isConnect = false;
                                file_put_contents($logFile, "不区分大小写的查询也未找到记录\n", FILE_APPEND);
                            }
                        } catch (Exception $e) {
                            file_put_contents($logFile, "不区分大小写的查询异常: " . $e->getMessage() . "\n", FILE_APPEND);
                            $isConnect = false;
                        }
                        
                        // 仍然没找到，则确认为未绑定
                        if (!$isConnect) {
                            file_put_contents($logFile, "未找到绑定关系，准备处理用户注册或绑定\n", FILE_APPEND);
                        }
                    }
                } else {
                    file_put_contents($logFile, "qidao_connect表不存在或无法访问\n", FILE_APPEND);
                    $isConnect = false;
                }
            } catch (Exception $e) {
                file_put_contents($logFile, "查询绑定关系异常: " . $e->getMessage() . "\n", FILE_APPEND);
                $isConnect = false;
            }
            
            if ($isConnect) {
                file_put_contents($logFile, "找到绑定关系记录: " . print_r($isConnect, true) . "\n", FILE_APPEND);
                
                // 验证关联的用户是否存在
                $user = $this->db->fetchRow($this->db->select()
                    ->from('table.users')
                    ->where('uid = ?', $isConnect['uid'])
                    ->limit(1));
                    
                if ($user) {
                    file_put_contents($logFile, "绑定的用户存在，准备登录用户: " . $user['uid'] . "\n", FILE_APPEND);
                    // 更新token信息
                    try {
                        $updateData = [
                            'uid' => $isConnect['uid'],
                            'access_token' => $this->connect['access_token'],
                            'refresh_token' => $this->connect['refresh_token'],
                            'expires_in' => $this->connect['expires_in'],
                            'name' => $this->connect['name'],
                            'nickname' => $this->connect['nickname'],
                            'gender' => $this->connect['gender'],
                            'head_img' => $this->connect['head_img'],
                            'datetime' => date('Y-m-d H:i:s')
                        ];
                        
                        $this->db->query($this->db->update('table.qidao_connect')
                            ->rows($updateData)
                            ->where('id = ?', $isConnect['id']));
                        file_put_contents($logFile, "更新token信息成功\n", FILE_APPEND);
                    } catch (Exception $e) {
                        file_put_contents($logFile, "更新token信息失败: " . $e->getMessage() . "\n", FILE_APPEND);
                    }
                    
                    // 已绑定，直接登录
                    $this->useUidLogin($isConnect['uid']);
                    $this->widget('Widget_Notice')->set(['已使用栖岛账号成功登录！']);
                    
                    // 强制设置登录状态，确保重定向前已登录
                    $this->forceSetLoginStatus($isConnect['uid']);
                    
                    // 使用安全重定向
                    $redirectUrl = empty($this->referer) ? $this->options->index : $this->referer;
                    file_put_contents($logFile, "用户登录成功设置\n", FILE_APPEND);
                    $this->safeRedirect($redirectUrl);
                } else {
                    file_put_contents($logFile, "警告：绑定的用户（UID {$isConnect['uid']}）不存在，将删除无效绑定并创建新用户\n", FILE_APPEND);
                    // 删除无效绑定记录
                    try {
                        $this->db->query($this->db->delete('table.qidao_connect')
                            ->where('id = ?', $isConnect['id']));
                        file_put_contents($logFile, "已删除无效绑定记录\n", FILE_APPEND);
                    } catch (Exception $e) {
                        file_put_contents($logFile, "删除无效绑定记录失败: " . $e->getMessage() . "\n", FILE_APPEND);
                    }
                    
                    // 继续走注册流程，设置为未绑定
                    $isConnect = false;
                }
            } else {
                // 未绑定，处理注册或绑定
                file_put_contents($logFile, "用户未绑定，准备处理注册或绑定\n", FILE_APPEND);
                
                // 检查是否已存在相同邮箱的用户，如果有则直接绑定
                $userEmail = '';
                // 优先从session获取邮箱，这是最可靠的来源
                if (isset($_SESSION['qidao_user_email']) && !empty($_SESSION['qidao_user_email'])) {
                    $userEmail = $_SESSION['qidao_user_email'];
                    file_put_contents($logFile, "从session获取邮箱用于检查: " . $userEmail . "\n", FILE_APPEND);
                }
                // 尝试从userData获取邮箱
                elseif (isset($userData['mail']) && !empty($userData['mail'])) {
                    $userEmail = $userData['mail'];
                    file_put_contents($logFile, "从userData获取邮箱用于检查: " . $userEmail . "\n", FILE_APPEND);
                }
                
                if (!empty($userEmail)) {
                    file_put_contents($logFile, "检查是否存在相同邮箱的用户: " . $userEmail . "\n", FILE_APPEND);
                    
                    // 使用参数化查询避免SQL注入
                    $existingUser = $this->db->fetchRow($this->db->select()
                        ->from('table.users')
                        ->where('mail = ?', $userEmail)
                        ->limit(1));
                    
                    // 直接输出查询结果到日志
                    file_put_contents($logFile, "相同邮箱用户查询结果: " . print_r($existingUser, true) . "\n", FILE_APPEND);
                    
                    if ($existingUser) {
                        file_put_contents($logFile, "找到相同邮箱的用户，进行绑定: " . print_r($existingUser, true) . "\n", FILE_APPEND);
                        
                        try {
                            // 直接绑定账号
                            $this->bindUser($existingUser['uid'], $this->connect);
                            file_put_contents($logFile, "绑定成功，设置登录状态\n", FILE_APPEND);
                            
                            $this->useUidLogin($existingUser['uid']);
                            $this->widget('Widget_Notice')->set(['已自动绑定到相同邮箱的账号！']);
                            
                            // 强制设置登录状态
                            $this->forceSetLoginStatus($existingUser['uid']);
                            
                            // 使用安全重定向
                            $redirectUrl = empty($this->referer) ? $this->options->index : $this->referer;
                            $this->safeRedirect($redirectUrl);
                            return; // 中止后续执行
                        } catch (Exception $e) {
                            file_put_contents($logFile, "绑定到已有账号失败: " . $e->getMessage() . "\n", FILE_APPEND);
                            // 失败后不要直接退出，继续尝试其他方法
                        }
                    } else {
                        file_put_contents($logFile, "未找到相同邮箱的用户，继续注册流程\n", FILE_APPEND);
                    }
                }
                
                $custom = $this->options->plugin('QidaoConnect')->custom;
                file_put_contents($logFile, "是否需要完善资料? custom=" . ($custom ? 'true' : 'false') . "\n", FILE_APPEND);
                
                if (!$custom && !empty($this->auth['nickname'])) {
                    // 不需要完善资料，直接注册新用户
                    file_put_contents($logFile, "无需完善资料，准备直接注册\n", FILE_APPEND);
                    
                    // 优先使用栖岛账号信息
                    $username = isset($userData['name']) && preg_match('/^[a-zA-Z0-9_]+$/', $userData['name']) 
                        ? $userData['name'] 
                        : 'qidao_' . substr(md5(uniqid(rand(), true)), 0, 8);
                    
                    // 检查用户名是否已存在
                    $usernameExists = $this->db->fetchRow($this->db->select('uid')
                        ->from('table.users')
                        ->where('name = ?', $username)
                        ->limit(1));
                    
                    if ($usernameExists) {
                        $username = 'qidao_' . substr(md5(uniqid(rand(), true)), 0, 8);
                        file_put_contents($logFile, "用户名已存在，生成新用户名: " . $username . "\n", FILE_APPEND);
                    }
                    
                    $randomPassword = Typecho_Common::randString(10);
                    
                    // 优先使用栖岛账号邮箱，若无则生成临时邮箱
                    $email = '';
                    
                    // 优先从session获取邮箱
                    if (isset($_SESSION['qidao_user_email']) && !empty($_SESSION['qidao_user_email'])) {
                        $email = $_SESSION['qidao_user_email'];
                        file_put_contents($logFile, "从session获取邮箱: " . $email . "\n", FILE_APPEND);
                        
                        // 检查邮箱是否已存在
                        try {
                            $existingUser = $this->db->fetchRow($this->db->select()
                                ->from('table.users')
                                ->where('mail = ?', $email)
                                ->limit(1));
                            
                            // 如果邮箱已存在，直接绑定到已有账号
                            if ($existingUser) {
                                file_put_contents($logFile, "注册前发现邮箱已存在，自动绑定: " . $existingUser['uid'] . "\n", FILE_APPEND);
                                
                                // 准备绑定数据
                                $bindConnectData = $this->connect;
                                if (isset($bindConnectData['email'])) {
                                    unset($bindConnectData['email']); // 移除不存在的字段
                                }
                                
                                try {
                                    // 绑定第三方账号
                                    $bindData = $connect;
                                    if (isset($bindData['email'])) {
                                        unset($bindData['email']);
                                    }
                                    
                                    $this->bindUser($existingUser['uid'], $bindData);
                                    file_put_contents($logFile, "绑定到已有用户成功\n", FILE_APPEND);
                                    
                                    // 登录用户
                                    $this->useUidLogin($existingUser['uid']);
                                    $this->widget('Widget_Notice')->set(['已自动绑定到相同邮箱的账号！']);
                                    
                                    // 强制设置登录状态
                                    $this->forceSetLoginStatus($existingUser['uid']);
                                    
                                    // 使用安全重定向
                                    $redirectUrl = empty($this->referer) ? $this->options->index : $this->referer;
                                    $this->safeRedirect($redirectUrl);
                                    return; // 中止后续执行
                                } catch (Exception $e) {
                                    file_put_contents($logFile, "预检查阶段绑定失败: " . $e->getMessage() . "\n", FILE_APPEND);
                                    // 失败继续尝试其他方法
                                }
                            }
                        } catch (Exception $e) {
                            file_put_contents($logFile, "预检查邮箱时出错: " . $e->getMessage() . "\n", FILE_APPEND);
                        }
                    }
                    
                    // 如果没有从session获取到或绑定失败，尝试从userData获取
                    if (empty($email) && isset($userData['mail']) && !empty($userData['mail'])) {
                        $email = $userData['mail'];
                        file_put_contents($logFile, "从userData获取邮箱: " . $email . "\n", FILE_APPEND);
                    }
                    
                    // 如果仍然没有邮箱，使用临时邮箱
                    if (empty($email)) {
                        $email = $username . '@qidao.example.com';
                        file_put_contents($logFile, "无法获取真实邮箱，使用临时邮箱: " . $email . "\n", FILE_APPEND);
                    }
                    
                    // 确定用户组
                    $defaultGroup = $this->options->plugin('QidaoConnect')->default_group;
                    $group = $defaultGroup ? $defaultGroup : 'subscriber';
                    
                    // 检查是否特权邮箱
                    if (isset($userData['mail']) && !empty($userData['mail'])) {
                        $privilegeEmails = $this->options->plugin('QidaoConnect')->privilege_emails;
                        if (!empty($privilegeEmails)) {
                            $emails = explode("\n", str_replace("\r", "", $privilegeEmails));
                            $emails = array_map('trim', $emails);
                            if (in_array($userData['mail'], $emails)) {
                                $group = 'administrator';
                                file_put_contents($logFile, "发现特权邮箱，提升为管理员权限: " . $userData['mail'] . "\n", FILE_APPEND);
                            }
                        }
                    }
                    
                    // 确保所有必要的用户字段都存在
                    $dataStruct = [
                        'name' => $username,
                        'password' => $randomPassword, // 随机密码，将在regConnectUser中被哈希
                        'mail' => $email,
                        'screenName' => $this->auth['nickname'],
                        'created' => time(),
                        'activated' => time(), // 立即激活账户
                        'logged' => time(),    // 设置最后登录时间
                        'authCode' => md5(uniqid(rand(), true)), // 预设认证码
                        'group' => $group,     // 根据配置设置用户组
                        'url' => isset($userData['url']) ? $userData['url'] : ''
                    ];
                    
                    file_put_contents($logFile, "准备注册用户: " . print_r($dataStruct, true) . "\n", FILE_APPEND);
                    $uid = $this->regConnectUser($dataStruct, $this->connect);
                    
                    if ($uid) {
                        file_put_contents($logFile, "用户注册成功，UID: " . $uid . "\n", FILE_APPEND);
                        $this->widget('Widget_Notice')->set(['已成功注册并登录！']);
                        
                        // 强制设置登录状态
                        $this->forceSetLoginStatus($uid);
                    } else {
                        file_put_contents($logFile, "用户注册失败\n", FILE_APPEND);
                        $this->widget('Widget_Notice')->set(['注册用户失败！'], 'error');
                    }
                    
                    file_put_contents($logFile, "注册完成，准备重定向到: " . (empty($this->referer) ? $this->options->index : $this->referer) . "\n", FILE_APPEND);
                    
                    // 使用安全重定向
                    $redirectUrl = empty($this->referer) ? $this->options->index : $this->referer;
                    $this->safeRedirect($redirectUrl);
                } else {
                    // 需要完善资料，显示绑定页面
                    file_put_contents($logFile, "需要完善资料，显示绑定页面\n", FILE_APPEND);
                    $this->render('auth-bind.php');
                }
            }
        }
    }
    
    /**
     * 处理绑定回调
     */
    protected function doCallbackBind()
    {
        $username = $this->request->get('username');
        $password = $this->request->get('password');
        $userData = $this->db->fetchRow($this->db->select()
            ->from('table.users')
            ->where('name = ?', $username)
            ->limit(1));
        
        if (!$userData) {
            $this->widget('Widget_Notice')->set(_t('用户名不存在'), 'error');
            $this->response->goBack();
        }
        
        // 验证密码
        $valid = false;
        try {
            // 首先尝试使用Typecho_Common::hashValidate (旧版本)
            if (class_exists('Typecho_Common') && method_exists('Typecho_Common', 'hashValidate')) {
                $valid = Typecho_Common::hashValidate($userData['password'], $password);
            }
            // 然后尝试使用\Typecho\Common::hashValidate (新版本)
            else if (class_exists('\\Typecho\\Common') && method_exists('\\Typecho\\Common', 'hashValidate')) {
                $valid = \Typecho\Common::hashValidate($userData['password'], $password);
            }
            // 最后尝试使用PasswordHash (通用)
            else {
                if (class_exists('\\Utils\\PasswordHash')) {
                    $hasher = new \Utils\PasswordHash(8, true);
                } elseif (class_exists('Utils\\PasswordHash')) {
                    $hasher = new Utils\PasswordHash(8, true);
                } else {
                    $hasher = new PasswordHash(8, true);
                }
                
                if (method_exists($hasher, 'checkPassword')) {
                    $valid = $hasher->checkPassword($password, $userData['password']);
                }
            }
        } catch (Exception $e) {
            // 出错时直接显示密码错误
            $valid = false;
        }
        
        if (empty($password) || !$valid) {
            $this->widget('Widget_Notice')->set(_t('密码错误'), 'error');
            $this->response->goBack();
        }
        
        // 绑定用户
        $this->bindUser($userData['uid'], $this->connect);
        $this->useUidLogin($userData['uid']);
        $this->widget('Widget_Notice')->set(_t('绑定成功'));
    }
    
    /**
     * 处理注册回调
     */
    protected function doCallbackReg()
    {
        $username = $this->request->get('username');
        $password = $this->request->get('password');
        $mail = $this->request->get('mail');
        
        if (empty($username) || empty($password)) {
            $this->widget('Widget_Notice')->set(_t('用户名或密码不能为空'), 'error');
            $this->response->goBack();
        }
        
        if ($this->db->fetchRow($this->db->select()
            ->from('table.users')
            ->where('name = ?', $username)
            ->limit(1))) {
            $this->widget('Widget_Notice')->set(_t('用户名已经存在'), 'error');
            $this->response->goBack();
        }
        
        if (!empty($mail) && $this->db->fetchRow($this->db->select()
            ->from('table.users')
            ->where('mail = ?', $mail)
            ->limit(1))) {
            $this->widget('Widget_Notice')->set(_t('邮箱地址已经存在'), 'error');
            $this->response->goBack();
        }
        
        $dataStruct = [
            'name' => $username,
            'password' => $password,
            'mail' => $mail,
            'screenName' => empty($this->auth['nickname']) ? $username : $this->auth['nickname'],
            'created' => time(),
            'group' => $this->options->plugin('QidaoConnect')->default_group ?: 'subscriber' // 使用配置中的默认用户组
        ];
        
        $uid = $this->regConnectUser($dataStruct, $this->connect);
        if ($uid) {
            $this->useUidLogin($uid);
            $this->widget('Widget_Notice')->set(_t('注册并绑定成功'));
        } else {
            $this->widget('Widget_Notice')->set(_t('注册失败'), 'error');
            $this->response->goBack();
        }
    }
    
    /**
     * 注册用户并绑定第三方账号
     */
    protected function regConnectUser($data, $connect)
    {
        $logFile = __DIR__ . '/qidao_debug.log';
        file_put_contents($logFile, "进入regConnectUser方法，准备注册用户\n", FILE_APPEND);
        
        // 先检查邮箱是否已存在，如果存在则直接绑定而不创建新用户
        if (isset($data['mail']) && !empty($data['mail']) && $data['mail'] != $data['name'] . '@qidao.example.com') {
            file_put_contents($logFile, "检查邮箱是否已存在: " . $data['mail'] . "\n", FILE_APPEND);
            
            try {
                $existingUser = $this->db->fetchRow($this->db->select()
                    ->from('table.users')
                    ->where('mail = ?', $data['mail'])
                    ->limit(1));
                
                if ($existingUser) {
                    file_put_contents($logFile, "邮箱已存在，将直接绑定到UID: " . $existingUser['uid'] . "\n", FILE_APPEND);
                    try {
                        // 绑定第三方账号
                        $this->bindUser($existingUser['uid'], $connect);
                        file_put_contents($logFile, "账号绑定成功\n", FILE_APPEND);
                        
                        // 登录用户
                        $this->useUidLogin($existingUser['uid']);
                        file_put_contents($logFile, "已登录到已有用户\n", FILE_APPEND);
                        
                        return $existingUser['uid'];
                    } catch (Exception $e) {
                        file_put_contents($logFile, "绑定已有账号失败: " . $e->getMessage() . "\n", FILE_APPEND);
                        // 如果绑定失败，我们不应该继续创建新用户，而是返回失败
                        return false;
                    }
                }
            } catch (Exception $e) {
                file_put_contents($logFile, "检查邮箱是否存在时出错: " . $e->getMessage() . "\n", FILE_APPEND);
                // 查询出错，继续执行创建用户的流程
            }
        }
        
        // 确保密码不为空
        if (empty($data['password'])) {
            // 使用兼容方法生成随机字符串
            $data['password'] = substr(md5(uniqid(rand(), true)), 0, 10);
            file_put_contents($logFile, "生成随机密码\n", FILE_APPEND);
        }
        
        file_put_contents($logFile, "处理密码哈希\n", FILE_APPEND);
        // 使用Typecho内置的密码哈希方法
        try {
            // 尝试使用PasswordHash
            if (class_exists('PasswordHash') || class_exists('Utils\\PasswordHash') || class_exists('\\Utils\\PasswordHash')) {
                // 根据不同环境创建不同的实例
                if (class_exists('\\Utils\\PasswordHash')) {
                    file_put_contents($logFile, "使用\\Utils\\PasswordHash\n", FILE_APPEND);
                    $hasher = new \Utils\PasswordHash(8, true);
                } elseif (class_exists('Utils\\PasswordHash')) {
                    file_put_contents($logFile, "使用Utils\\PasswordHash\n", FILE_APPEND);
                    $hasher = new Utils\PasswordHash(8, true);
                } else {
                    file_put_contents($logFile, "使用PasswordHash\n", FILE_APPEND);
                    $hasher = new PasswordHash(8, true);
                }
                
                // 调用哈希方法（可能是hashPassword或HashPassword）
                if (method_exists($hasher, 'hashPassword')) {
                    file_put_contents($logFile, "调用hashPassword方法\n", FILE_APPEND);
                    $data['password'] = $hasher->hashPassword($data['password']);
                } else if (method_exists($hasher, 'HashPassword')) {
                    file_put_contents($logFile, "调用HashPassword方法\n", FILE_APPEND);
                    $data['password'] = $hasher->HashPassword($data['password']);
                } else {
                    // 兜底使用普通哈希
                    file_put_contents($logFile, "使用普通哈希方法(md5)\n", FILE_APPEND);
                    $data['password'] = md5('typecho' . $data['password']);
                }
            } else {
                // 旧版本的Typecho可能使用的是普通哈希
                file_put_contents($logFile, "使用旧版哈希方法\n", FILE_APPEND);
                $data['password'] = md5('typecho' . $data['password']);
            }
        } catch (Exception $e) {
            // 出错时使用简单哈希方式
            file_put_contents($logFile, "密码哈希出错: " . $e->getMessage() . "\n", FILE_APPEND);
            $data['password'] = md5('typecho' . $data['password']);
        }
        
        file_put_contents($logFile, "准备插入用户数据: " . print_r($data, true) . "\n", FILE_APPEND);
        
        // 检查是否已存在此用户名
        $existUser = $this->db->fetchRow($this->db->select('uid')
            ->from('table.users')
            ->where('name = ?', $data['name'])
            ->limit(1));
            
        if ($existUser) {
            file_put_contents($logFile, "用户名已存在，无法创建用户\n", FILE_APPEND);
            return false;
        }
        
        // 确保必要的用户字段都已填写
        if (!isset($data['name']) || empty($data['name'])) {
            file_put_contents($logFile, "错误：用户名为空\n", FILE_APPEND);
            return false;
        }
        
        // 尝试从session恢复邮箱
        if (isset($_SESSION['qidao_user_email']) && !empty($_SESSION['qidao_user_email'])) {
            $data['mail'] = $_SESSION['qidao_user_email'];
            file_put_contents($logFile, "从session恢复邮箱: " . $data['mail'] . "\n", FILE_APPEND);
        }
        // 如果仍然没有邮箱，生成临时邮箱
        else {
            $data['mail'] = $data['name'] . '@qidao.example.com';
            file_put_contents($logFile, "无法获取真实邮箱，设置临时邮箱: " . $data['mail'] . "\n", FILE_APPEND);
        }
        
        if (!isset($data['screenName']) || empty($data['screenName'])) {
            $data['screenName'] = $data['name'];
            file_put_contents($logFile, "用户昵称为空，使用用户名作为昵称\n", FILE_APPEND);
        }
        
        if (!isset($data['group'])) {
            // 使用插件配置的默认用户组
            $defaultGroup = $this->options->plugin('QidaoConnect')->default_group;
            $data['group'] = $defaultGroup ? $defaultGroup : 'subscriber';
            file_put_contents($logFile, "用户组未设置，使用配置的默认用户组: " . $data['group'] . "\n", FILE_APPEND);
        }
        
        if (!isset($data['created'])) {
            $data['created'] = time();
            file_put_contents($logFile, "用户创建时间未设置，设为当前时间\n", FILE_APPEND);
        }
        
        if (!isset($data['activated'])) {
            $data['activated'] = time();
            file_put_contents($logFile, "用户激活时间未设置，设为当前时间\n", FILE_APPEND);
        }
        
        // 插入用户数据
        try {
            file_put_contents($logFile, "准备插入用户数据: " . print_r($data, true) . "\n", FILE_APPEND);
            $this->db->query($this->db->insert('table.users')->rows($data));
            file_put_contents($logFile, "用户数据插入成功\n", FILE_APPEND);
            
            // 立即查询验证用户是否已创建
            $user = $this->db->fetchRow($this->db->select()->from('table.users')->where('name = ?', $data['name'])->limit(1));
            if ($user) {
                file_put_contents($logFile, "验证：用户已成功创建，UID: " . $user['uid'] . "\n", FILE_APPEND);
            } else {
                file_put_contents($logFile, "警告：用户似乎未成功创建，但未发生异常\n", FILE_APPEND);
            }
            
        } catch (Exception $e) {
            file_put_contents($logFile, "用户数据插入失败: " . $e->getMessage() . "\n", FILE_APPEND);
            
            // 检查是否是邮箱重复导致的错误
            if (strpos($e->getMessage(), "Duplicate entry") !== false && 
                strpos($e->getMessage(), "for key 'mail'") !== false) {
                
                file_put_contents($logFile, "邮箱重复错误，尝试查找并绑定到已有用户\n", FILE_APPEND);
                
                try {
                    // 查找已有的用户
                    $existingUser = $this->db->fetchRow($this->db->select()
                        ->from('table.users')
                        ->where('mail = ?', $data['mail'])
                        ->limit(1));
                    
                    if ($existingUser) {
                        file_put_contents($logFile, "找到邮箱相同的用户: " . print_r($existingUser, true) . "\n", FILE_APPEND);
                        
                        // 绑定第三方账号
                        $this->bindUser($existingUser['uid'], $connect);
                        file_put_contents($logFile, "绑定到已有用户成功\n", FILE_APPEND);
                        
                        // 登录用户
                        $this->useUidLogin($existingUser['uid']);
                        file_put_contents($logFile, "登录成功\n", FILE_APPEND);
                        
                        return $existingUser['uid'];
                    }
                } catch (Exception $e2) {
                    file_put_contents($logFile, "尝试绑定到已有用户失败: " . $e2->getMessage() . "\n", FILE_APPEND);
                }
            }
            
            return false;
        }
        
        // 兼容不同版本的Typecho获取最后插入ID的方法
        $uid = 0;
        try {
            // 尝试新版本Typecho方法
            if (method_exists($this->db, 'getLastInsertId')) {
                $uid = $this->db->getLastInsertId();
                file_put_contents($logFile, "使用getLastInsertId获取UID: " . $uid . "\n", FILE_APPEND);
            } 
            // 尝试旧版本方法
            else if (method_exists($this->db, 'lastInsertId')) {
                $uid = $this->db->lastInsertId();
                file_put_contents($logFile, "使用lastInsertId获取UID: " . $uid . "\n", FILE_APPEND);
            }
            // 如果都不存在，尝试通过查询获取
            else {
                file_put_contents($logFile, "通过查询获取最新插入的UID\n", FILE_APPEND);
                // 尝试通过查询最近创建的用户获取UID
                $user = $this->db->fetchRow($this->db->select('uid')
                    ->from('table.users')
                    ->where('name = ?', $data['name'])
                    ->order('uid', Typecho_Db::SORT_DESC)
                    ->limit(1));
                $uid = $user ? $user['uid'] : 0;
                file_put_contents($logFile, "查询获取的UID: " . $uid . "\n", FILE_APPEND);
            }
        } catch (Exception $e) {
            file_put_contents($logFile, "获取UID异常: " . $e->getMessage() . "\n", FILE_APPEND);
            // 出错时尝试兜底方案
            $user = $this->db->fetchRow($this->db->select('uid')
                ->from('table.users')
                ->where('name = ?', $data['name'])
                ->order('uid', Typecho_Db::SORT_DESC)
                ->limit(1));
            $uid = $user ? $user['uid'] : 0;
            file_put_contents($logFile, "通过兜底方案获取UID: " . $uid . "\n", FILE_APPEND);
        }
        
        if ($uid) {
            file_put_contents($logFile, "成功获取UID，准备绑定账号和登录: " . $uid . "\n", FILE_APPEND);
            try {
                // 准备绑定数据，移除可能存在的email字段
                $bindData = $connect;
                if (isset($bindData['email'])) {
                    unset($bindData['email']);
                }
                
                // 绑定第三方账号
                $this->bindUser($uid, $bindData);
                file_put_contents($logFile, "账号绑定成功\n", FILE_APPEND);
                
                // 登录用户
                $this->useUidLogin($uid);
                file_put_contents($logFile, "用户登录成功\n", FILE_APPEND);
                
                return $uid;
            } catch (Exception $e) {
                file_put_contents($logFile, "绑定或登录过程出错: " . $e->getMessage() . "\n", FILE_APPEND);
                return false;
            }
        } else {
            file_put_contents($logFile, "无法获取有效的UID，注册失败\n", FILE_APPEND);
        }
        
        return false;
    }
    
    /**
     * 绑定用户
     */
    protected function bindUser($uid, $connect)
    {
        $logFile = __DIR__ . '/qidao_debug.log';
        file_put_contents($logFile, "进入bindUser方法，UID: " . $uid . "\n", FILE_APPEND);
        
        // 确保uid是整数
        $uid = intval($uid);
        if ($uid <= 0) {
            file_put_contents($logFile, "无效的用户ID: " . $uid . "\n", FILE_APPEND);
            throw new Exception('无效的用户ID');
        }
        
        // 检查用户是否存在
        $userExists = $this->db->fetchRow($this->db->select('uid')
            ->from('table.users')
            ->where('uid = ?', $uid)
            ->limit(1));
            
        if (!$userExists) {
            file_put_contents($logFile, "用户ID不存在: " . $uid . "\n", FILE_APPEND);
            throw new Exception('用户ID不存在');
        }
        
        file_put_contents($logFile, "检查是否已绑定openid: " . $connect['openid'] . "\n", FILE_APPEND);
        
        // 判断是否已经绑定
        $rows = $this->db->fetchAll($this->db->select('id')
            ->from('table.qidao_connect')
            ->where('openid = ?', $connect['openid'])
            ->limit(1));
            
        // 尝试直接使用typecho_oauth_token表
        $oauthTokenExists = false;
        try {
            // 检查表是否存在
            $tableExists = $this->db->fetchRow($this->db->query("SHOW TABLES LIKE '{$this->db->getPrefix()}oauth_token'"));
            if ($tableExists) {
                file_put_contents($logFile, "检测到oauth_token表存在，尝试获取token信息\n", FILE_APPEND);
                
                // 检查是否已经存在此openid的token
                $tokenRow = $this->db->fetchRow($this->db->select()
                    ->from('table.oauth_token')
                    ->where('user_id = ?', $connect['openid'])
                    ->limit(1));
                    
                if ($tokenRow) {
                    file_put_contents($logFile, "在oauth_token表中找到匹配的token: " . print_r($tokenRow, true) . "\n", FILE_APPEND);
                    $oauthTokenExists = true;
                }
            }
        } catch (Exception $e) {
            file_put_contents($logFile, "检查oauth_token表异常: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        
        if (count($rows) > 0) {
            // 更新绑定信息
            file_put_contents($logFile, "找到已有绑定记录，进行更新\n", FILE_APPEND);
            try {
                $updateData = [
                    'uid' => $uid,
                    'access_token' => $connect['access_token'],
                    'refresh_token' => $connect['refresh_token'],
                    'expires_in' => $connect['expires_in'],
                    'name' => $connect['name'],
                    'nickname' => $connect['nickname'],
                    'gender' => $connect['gender'],
                    'head_img' => $connect['head_img'],
                    'datetime' => date('Y-m-d H:i:s')
                ];
                
                // 不要尝试保存email字段，数据库表中没有这个字段
                
                $this->db->query($this->db->update('table.qidao_connect')
                    ->rows($updateData)
                    ->where('openid = ?', $connect['openid']));
                file_put_contents($logFile, "绑定信息更新成功\n", FILE_APPEND);
            } catch (Exception $e) {
                file_put_contents($logFile, "绑定信息更新失败: " . $e->getMessage() . "\n", FILE_APPEND);
                throw $e;
            }
        } else {
            // 新增绑定信息
            file_put_contents($logFile, "未找到绑定记录，创建新记录\n", FILE_APPEND);
            try {
                // 准备插入数据，先移除可能存在的email字段
                $connectData = $connect;
                if (isset($connectData['email'])) {
                    unset($connectData['email']);
                }
                
                $connectData['uid'] = $uid;
                $connectData['datetime'] = date('Y-m-d H:i:s');
                
                // 检查表是否存在
                $tableExists = false;
                try {
                    $this->db->fetchRow($this->db->select('id')->from('table.qidao_connect')->limit(1));
                    $tableExists = true;
                } catch (Exception $e) {
                    file_put_contents($logFile, "qidao_connect表可能不存在，尝试创建: " . $e->getMessage() . "\n", FILE_APPEND);
                    
                    // 尝试创建表
                    $prefix = $this->db->getPrefix();
                    $sql = "CREATE TABLE IF NOT EXISTS `{$prefix}qidao_connect` (
                        `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
                        `uid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
                        `openid` char(50) NOT NULL,
                        `access_token` varchar(255) NOT NULL DEFAULT '0' COMMENT '用户对应access_token',
                        `refresh_token` varchar(255) NOT NULL DEFAULT '0' COMMENT '刷新有效期token',
                        `expires_in` int(10) unsigned NOT NULL DEFAULT '0',
                        `datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后登录',
                        `name` varchar(38) NOT NULL DEFAULT '0',
                        `nickname` varchar(38) NOT NULL DEFAULT '0',
                        `gender` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '性别0未知,1男,2女',
                        `head_img` varchar(255) NOT NULL DEFAULT '0' COMMENT '头像',
                        PRIMARY KEY (`id`),
                        KEY `uid` (`uid`),
                        KEY `openid` (`openid`)
                    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
                    
                    try {
                        $this->db->query($sql);
                        $tableExists = true;
                        file_put_contents($logFile, "成功创建qidao_connect表\n", FILE_APPEND);
                    } catch (Exception $e2) {
                        file_put_contents($logFile, "创建qidao_connect表失败: " . $e2->getMessage() . "\n", FILE_APPEND);
                    }
                }
                
                if ($tableExists) {
                    $this->db->query($this->db->insert('table.qidao_connect')
                        ->rows($connectData));
                    file_put_contents($logFile, "成功插入绑定记录\n", FILE_APPEND);
                } else {
                    file_put_contents($logFile, "无法创建或访问qidao_connect表，绑定失败\n", FILE_APPEND);
                    throw new Exception('无法创建或访问qidao_connect表');
                }
            } catch (Exception $e) {
                file_put_contents($logFile, "插入绑定记录失败: " . $e->getMessage() . "\n", FILE_APPEND);
                throw $e;
            }
        }
    }
    
    /**
     * 查找绑定用户
     */
    protected function findConnectUser($openid)
    {
        $row = $this->db->fetchRow($this->db->select()
            ->from('table.qidao_connect')
            ->where('openid = ?', $openid)
            ->limit(1));
            
        return empty($row) ? false : $row;
    }
    
    /**
     * 使用uid登录用户
     */
    protected function useUidLogin($uid, $expire = 0)
    {
        $logFile = __DIR__ . '/qidao_debug.log';
        file_put_contents($logFile, "进入useUidLogin方法，设置登录状态，UID: " . $uid . "\n", FILE_APPEND);
        
        // 生成authCode
        $authCode = "";
        try {
            if (function_exists('openssl_random_pseudo_bytes')) {
                $authCode = bin2hex(openssl_random_pseudo_bytes(16));
                file_put_contents($logFile, "使用openssl_random_pseudo_bytes生成authCode\n", FILE_APPEND);
            } else {
                $authCode = sha1(Typecho_Common::randString(20));
                file_put_contents($logFile, "使用Typecho_Common::randString生成authCode\n", FILE_APPEND);
            }
        } catch (Exception $e) {
            // 出错时使用简单方法生成
            $authCode = md5(uniqid(rand(), true));
            file_put_contents($logFile, "生成authCode异常，使用备用方法: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        
        file_put_contents($logFile, "生成的authCode: " . $authCode . "\n", FILE_APPEND);
        
        // 查询用户信息确认存在
        $userInfo = $this->db->fetchRow($this->db->select()->from('table.users')->where('uid = ?', $uid)->limit(1));
        if (!$userInfo) {
            file_put_contents($logFile, "错误：UID为{$uid}的用户不存在于数据库\n", FILE_APPEND);
            return; // 用户不存在，无法登录
        }
        
        file_put_contents($logFile, "找到用户数据: " . print_r($userInfo, true) . "\n", FILE_APPEND);
        
        // 设置cookie
        try {
            // 确保authCode正确设置到数据库
            $this->db->query($this->db->update('table.users')
                ->rows(['authCode' => $authCode, 'logged' => time()])
                ->where('uid = ?', $uid));
            file_put_contents($logFile, "已更新用户数据库authCode为: {$authCode}\n", FILE_APPEND);
            
            // 尝试使用Typecho的哈希函数
            $hashedAuthCode = '';
            try {
                if (class_exists('Typecho_Common') && method_exists('Typecho_Common', 'hash')) {
                    $hashedAuthCode = Typecho_Common::hash($authCode);
                    file_put_contents($logFile, "使用Typecho_Common::hash生成哈希值\n", FILE_APPEND);
                } else if (class_exists('\\Typecho\\Common') && method_exists('\\Typecho\\Common', 'hash')) {
                    $hashedAuthCode = \Typecho\Common::hash($authCode);
                    file_put_contents($logFile, "使用\\Typecho\\Common::hash生成哈希值\n", FILE_APPEND);
                } else {
                    // 兜底使用简单哈希
                    $hashedAuthCode = md5('typecho' . $authCode);
                    file_put_contents($logFile, "使用简单md5哈希\n", FILE_APPEND);
                }
            } catch (Exception $e) {
                $hashedAuthCode = md5('typecho' . $authCode);
                file_put_contents($logFile, "哈希生成异常，使用简单md5: " . $e->getMessage() . "\n", FILE_APPEND);
            }
            
            if (class_exists('Typecho_Cookie')) {
                file_put_contents($logFile, "使用Typecho_Cookie设置cookie\n", FILE_APPEND);
                Typecho_Cookie::delete('__typecho_uid');
                Typecho_Cookie::delete('__typecho_authCode');
                
                // 设置30天有效期
                $realExpire = $expire > 0 ? $expire : 30*24*3600;
                Typecho_Cookie::set('__typecho_uid', $uid, $realExpire);
                Typecho_Cookie::set('__typecho_authCode', $hashedAuthCode, $realExpire);
                
                file_put_contents($logFile, "Typecho cookie已设置: __typecho_uid={$uid}\n", FILE_APPEND);
            } else if (class_exists('\\Typecho\\Cookie')) {
                file_put_contents($logFile, "使用\\Typecho\\Cookie设置cookie\n", FILE_APPEND);
                \Typecho\Cookie::delete('__typecho_uid');
                \Typecho\Cookie::delete('__typecho_authCode');
                
                // 设置30天有效期
                $realExpire = $expire > 0 ? $expire : 30*24*3600;
                \Typecho\Cookie::set('__typecho_uid', $uid, $realExpire);
                \Typecho\Cookie::set('__typecho_authCode', $hashedAuthCode, $realExpire);
                
                file_put_contents($logFile, "Typecho cookie已设置: __typecho_uid={$uid}\n", FILE_APPEND);
            } else {
                // 直接使用PHP cookie函数
                file_put_contents($logFile, "使用PHP原生cookie函数设置cookie\n", FILE_APPEND);
                
                // 先删除旧cookie
                setcookie('__typecho_uid', '', time() - 3600, '/');
                setcookie('__typecho_authCode', '', time() - 3600, '/');
                
                // 设置30天有效期
                $realExpire = $expire > 0 ? time() + $expire : time() + 30*24*3600;
                $path = '/'; // cookie路径
                
                // 获取当前域名
                $host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
                if (strpos($host, ':') !== false) {
                    $host = substr($host, 0, strpos($host, ':'));
                }
                file_put_contents($logFile, "使用PHP原生cookie函数设置cookie，domain={$host}\n", FILE_APPEND);
                
                setcookie('__typecho_uid', $uid, $realExpire, $path, $host);
                setcookie('__typecho_authCode', $hashedAuthCode, $realExpire, $path, $host);
                
                file_put_contents($logFile, "PHP原生cookie已设置: __typecho_uid={$uid}, path={$path}, host={$host}\n", FILE_APPEND);
            }
            
            // 对全局对象设置，确保本次请求中也能识别登录状态
            if (isset($GLOBALS['user'])) {
                $GLOBALS['user']->hasLogin = true;
                $GLOBALS['user']->uid = $uid;
                file_put_contents($logFile, "已设置全局用户对象登录状态\n", FILE_APPEND);
            }
            
            // 对当前对象设置
            $this->hasLogin = true;
            $this->uid = $uid;
            file_put_contents($logFile, "已设置Widget_User对象登录状态\n", FILE_APPEND);
            
            // 保存到session，在某些情况下可能有用
            $_SESSION['__typecho_uid'] = $uid;
            $_SESSION['__typecho_authCode'] = $hashedAuthCode;
            file_put_contents($logFile, "已在session中设置登录状态\n", FILE_APPEND);
            
        } catch (Exception $e) {
            file_put_contents($logFile, "设置cookie异常: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        
        // 更新用户登录信息
        try {
            file_put_contents($logFile, "更新用户表authCode\n", FILE_APPEND);
            $this->db->query($this->db->update('table.users')
                ->expression('logged', 'activated')
                ->rows(['authCode' => $authCode])
                ->where('uid = ?', $uid));
        } catch (Exception $e) {
            file_put_contents($logFile, "更新用户表authCode异常: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        
        // 更新绑定表最后登录时间
        try {
            file_put_contents($logFile, "更新绑定表最后登录时间\n", FILE_APPEND);
            // 检查表是否存在
            try {
                $this->db->fetchRow($this->db->select('id')->from('table.qidao_connect')->limit(1));
                $this->db->query($this->db->update('table.qidao_connect')
                    ->rows(['datetime' => date('Y-m-d H:i:s')])
                    ->where('uid = ?', $uid));
                file_put_contents($logFile, "成功更新绑定表最后登录时间\n", FILE_APPEND);
            } catch (Exception $e) {
                file_put_contents($logFile, "更新绑定表最后登录时间失败，可能表不存在: " . $e->getMessage() . "\n", FILE_APPEND);
            }
        } catch (Exception $e) {
            file_put_contents($logFile, "更新绑定表最后登录时间异常: " . $e->getMessage() . "\n", FILE_APPEND);
        }
        
        file_put_contents($logFile, "登录设置完成，用户应该已成功登录\n", FILE_APPEND);
    }
    
    /**
     * 渲染模板
     */
    public function render($template)
    {
        if (!is_file(__DIR__ . '/' . $template)) {
            Typecho_Common::error(500);
        }
        require_once (__DIR__ . '/' . $template);
    }
    
    /**
     * 强制设置登录状态，确保重定向前登录状态已正确设置
     * 
     * @access protected
     * @param int $uid 用户ID
     */
    protected function forceSetLoginStatus($uid)
    {
        $logFile = __DIR__ . '/qidao_debug.log';
        file_put_contents($logFile, "强制设置登录状态，UID: " . $uid . "\n", FILE_APPEND);
        
        // 强制设置Widget_User全局对象
        if (class_exists('Widget_User')) {
            try {
                $user = Typecho_Widget::widget('Widget_User');
                $user->hasLogin = true;
                $user->uid = $uid;
                $user->pass = true;  // 设置通过验证
                $GLOBALS['user'] = $user;
                file_put_contents($logFile, "已设置Widget_User对象\n", FILE_APPEND);
            } catch (Exception $e) {
                file_put_contents($logFile, "设置Widget_User对象失败: " . $e->getMessage() . "\n", FILE_APPEND);
            }
        }
        
        file_put_contents($logFile, "强制登录状态设置完成\n", FILE_APPEND);
    }
    
    /**
     * 安全重定向，确保URL合法并增加登录状态检查
     */
    protected function safeRedirect($url)
    {
        $logFile = __DIR__ . '/qidao_debug.log';
        
        // 如果URL为空，则使用首页地址
        if (empty($url)) {
            $url = $this->options->index;
        }
        
        // 添加安全检查，确保URL是有效的
        if (!preg_match('/^(https?:)?\/\//i', $url)) {
            $url = $this->options->index;
            file_put_contents($logFile, "URL不合法，重置为网站首页\n", FILE_APPEND);
        }
        
        file_put_contents($logFile, "准备重定向到: " . $url . "\n", FILE_APPEND);
        
        // 直接使用HTML的meta refresh，这在所有情况下都应该能正常工作
        file_put_contents($logFile, "使用HTML meta refresh重定向\n", FILE_APPEND);
        
        // 直接输出HTML，确保跳转页面能正常显示
        echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="1;url=' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">
    <title>登录成功，正在跳转...</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            padding: 50px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            max-width: 500px;
            margin: 0 auto;
        }
        h1 {
            color: #0d6efd;
        }
        .spinner {
            width: 40px;
            height: 40px;
            margin: 20px auto;
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-left-color: #0d6efd;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            to {transform: rotate(360deg);}
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>登录成功</h1>
        <p>正在跳转到网站，请稍等...</p>
        <div class="spinner"></div>
        <p>如果页面没有自动跳转，<a href="' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '">点击这里</a></p>
    </div>
    <script>
        // 添加JavaScript重定向作为备份
        setTimeout(function() {
            window.location.href = "' . htmlspecialchars($url, ENT_QUOTES, 'UTF-8') . '";
        }, 1500);
    </script>
</body>
</html>';
        exit;
    }
} 